<!-- 添加类别 -->
<template>
    <div class="add-category">
        <div class="top">
            <div class="back" @click="$router.back()">
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M25 5L10 20L25 35" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="title">添加类别</div>
        </div>
        
        <div class="content">
            <div class="form-item">
                <div class="label">类别名称</div>
                <input type="text" v-model="categoryName" placeholder="请输入类别名称" :class="{ 'error': nameError }" />
                <div class="error-message" v-if="nameError">{{ nameError }}</div>
            </div>
            
            <div class="form-item">
                <div class="label">选择图标</div>
                <div v-if="loading" class="loading">
                    加载中...
                </div>
                <template v-else>
                    <div v-for="(icons, category) in iconList" 
                         :key="category" 
                         class="icon-category">
                        <!-- <div class="category-title">{{ category }}</div> -->
                        <div class="icon-grid">
                            <div v-for="icon in icons" 
                                 :key="icon._id"
                                 class="icon-item"
                                 :class="{ 'selected': selectedIcon === icon.icon_name }"
                                 @click="selectIcon(icon)">
                                 <svgIcon :iconName="icon.icon_name" font-size="100px"></svgIcon>
                                <!-- <span>{{ icon.name }}</span> -->
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        
        <div class="bottom">
            <button class="submit-btn" @click="handleSubmit">确定</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import svgIcon from '../components/svgIcon.vue';
import request from '../utils/request';

const router = useRouter();
const route = useRoute();

const categoryName = ref('');
const selectedIcon = ref('');
const currentType = ref(route.query.type || 'expense');
const iconList = ref([]);
const loading = ref(false);
const categories = ref([]);
const nameError = ref('');

// 监听类别名称变化
watch(categoryName, (newValue) => {
    if (!newValue.trim()) {
        nameError.value = '';
        return;
    }
    
    const categoryId = `${currentType.value}_${newValue.trim().toLowerCase().replace(/\s+/g, '_')}`;
    const existingCategory = categories.value.find(cat => cat.id === categoryId);
    
    if (existingCategory) {
        nameError.value = '该类别名称已存在，请更换其他名称';
    } else {
        nameError.value = '';
    }
});

// 获取图标列表
const fetchIcons = async () => {
    try {
        loading.value = true;
        const response = await request.get('/api/category/icons', null, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        // 按类别分组图标
        const groupedIcons = response.data.reduce((acc, icon) => {
            const category = icon.category || '其他';
            if (!acc[category]) {
                acc[category] = [];
            }
            acc[category].push(icon);
            return acc;
        }, {});
        iconList.value = groupedIcons;
        console.log(iconList.value);
    } catch (error) {
        console.error('获取图标失败:', error);
        alert('获取图标失败，请重试');
    } finally {
        loading.value = false;
    }
};

const selectIcon = (icon) => {
    console.log('选择的图标:', icon);
    selectedIcon.value = icon.icon_name;
};

const handleSubmit = async () => {
    if (!categoryName.value.trim()) {
        nameError.value = '请输入类别名称';
        return;
    }
    
    if (!selectedIcon.value) {
        alert('请选择图标');
        return;
    }

    // 检查类别名称是否已存在
    const categoryId = `${currentType.value}_${categoryName.value.trim().toLowerCase().replace(/\s+/g, '_')}`;
    const existingCategory = categories.value.find(cat => cat.id === categoryId);
    
    if (existingCategory) {
        nameError.value = '该类别名称已存在，请更换其他名称';
        return;
    }
    
    try {
        const categoryData = {
            name: categoryName.value.trim(),
            icon: selectedIcon.value,
            type: currentType.value,
            order: 0,
            data: []
        };

        console.log('准备提交的数据:', JSON.stringify(categoryData, null, 2));

        const response = await request.post('/api/category/categories', categoryData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('服务器响应:', JSON.stringify(response.data, null, 2));

        // 检查响应是否包含 _id，如果有则表示创建成功
        if (response.data && response.data._id) {
            console.log('添加类别成功:', response.data);
            router.back();
            return;
        }

        // 如果响应不包含 _id，则可能是其他错误情况
        throw new Error(response.data.message || '添加类别失败');
    } catch (error) {
        console.error('添加类别失败:', error);
        console.error('错误详情:', {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status
        });
        alert(error.message || '添加类别失败，请重试');
    }
};

// 获取现有类别列表
const fetchCategories = async () => {
    try {
        const response = await request.get('/api/category/categories', { params: { type: currentType.value } }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        categories.value = response.data;
    } catch (error) {
        console.error('获取类别列表失败:', error);
    }
};

// 组件挂载时获取数据
onMounted(() => {
    fetchIcons();
    fetchCategories();
});
</script>

<style lang="less" scoped>
.add-category {
    width: 100%;
    height: 100vh;
    background-color: #fff;
    position: relative;
    
    .top {
        width: 100%;
        height: 100px;
        background-color: #fb8fae;
        color: #fff;
        display: flex;
        align-items: center;
        padding: 0 20px;
        
        .back {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .title {
            font-size: 32px;
            margin-left: 20px;
        }
    }
    
    .content {
        padding: 20px;
        
        .form-item {
            margin-bottom: 30px;
            
            .label {
                font-size: 28px;
                color: #333;
                margin-bottom: 15px;
            }
            
            input {
                width: 100%;
                height: 80px;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 0 20px;
                font-size: 28px;
                
                &:focus {
                    border-color: #fb8fae;
                    outline: none;
                }

                &.error {
                    border-color: #ff4d4f;
                }
            }

            .error-message {
                color: #ff4d4f;
                font-size: 24px;
                margin-top: 10px;
                padding-left: 10px;
            }
            
            .icon-category {
                margin-bottom: 20px;
                
                .category-title {
                    font-size: 24px;
                    color: #666;
                    margin-bottom: 10px;
                    padding-left: 10px;
                }
                
                .icon-grid {
                    display: grid;
                    grid-template-columns: repeat(4, 1fr);
                    gap: 20px;
                    padding: 10px 0;
                    
                    .icon-item {
                        width: 100%;
                        aspect-ratio: 1;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        border: 1px solid #ddd;
                        border-radius: 8px;
                        cursor: pointer;
                        transition: all 0.3s ease;
                        padding: 10px;
                        
                        i {
                            font-size: 32px;
                            margin-bottom: 8px;
                        }
                        
                        .icon-name {
                            font-size: 24px;
                            color: #666;
                        }
                        
                        &:hover {
                            border-color: #fb8fae;
                            background-color: #fff5f8;
                        }
                        
                        &.selected {
                            border-color: #fb8fae;
                            background-color: #fff5f8;
                        }
                    }
                }
            }
        }
    }
    
    .bottom {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        padding: 20px;
        background-color: #fff;
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        
        .submit-btn {
            width: 100%;
            height: 80px;
            background-color: #fb8fae;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 32px;
            cursor: pointer;
            
            &:active {
                opacity: 0.8;
            }
        }
    }
}

.loading {
    text-align: center;
    padding: 20px;
    color: #666;
    font-size: 28px;
}
</style> 